package com.phone.handle;

import com.phone.entity.Token;
import com.phone.exception.TokenException;
import com.phone.utils.TextUtil;

/**
 * Created by tisen on 2017/9/13.
 */
public class TokenHandle extends EntityHandle<Token> {

    public boolean isTokenEffective(String tokenString) throws Exception {
        if (TextUtil.textIsEmpty(tokenString))
            throw new TokenException(TokenException.TOKEN_IS_EMPTY);
        Token token = (Token) session.createQuery("from Token where token = ''" + tokenString + "''").list().get(0);
        if (token == null)
            throw new TokenException(TokenException.TOKEN_NOT_EXIST);
        if (token.getTime() > System.currentTimeMillis())
            throw new TokenException(TokenException.TOKEN_TIMEOUT);
        return true;
    }

    public String regenerateToken(String id, long timeout) {
        String tokenString = getNewToken();
        Token token = new Token(id, tokenString, System.currentTimeMillis() + timeout);
        session.saveOrUpdate(token);
        return tokenString;
    }

    private String getNewToken() {
        return null;
    }
}
